package
{
	import com.puppy.httploader.Base64;
	import com.puppy.httploader.PuppyEvent;
	import com.puppy.httploader.PuppyLoader;
	import com.puppy.httploader.SocketURLLoader;
	
	import flash.display.Loader;
	import flash.display.SpreadMethod;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.events.NetStatusEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.TimerEvent;
	import flash.media.Video;
	import flash.net.NetConnection;
	import flash.net.NetStream;
	import flash.net.NetStreamAppendBytesAction;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.system.Security;
	import flash.system.SecurityDomain;
	import flash.text.TextField;
	import flash.utils.ByteArray;
	import flash.utils.Timer;
	
	public class PuppyLoad extends Sprite
	{
		private var _netStream:NetStream;
		private var _netConnect:NetConnection;
		
		private var _video:Video;
		
		private var videoURL:String = "http://www.xuehd.net/v-resource/111.f4v";
		private var CROSSDOMAIN:String = "http://www.xuehd.net/v-resource/crossdomain.xml";
		
		private var btnPlus:Sprite;
		
		private var keyframes:Object;
		private var pro:Pro = new Pro;
		private var nu:Number = 0;
		private var seektime:Number = 0;
		private var timer:Timer = new Timer(10);
		private var duration:Number = 0;
		private var endBytes:Number = 0;
		private var loadedTxt:TextField = new TextField();
		private var curTimeTxt:TextField = new TextField();
		private var loading:LoadingIndicator;
		
		public function PuppyLoad()
		{
			var isLocal:Boolean = true;
			if(isLocal)
			{
				videoURL = "http://192.168.9.192/resource/111.f4v";
				CROSSDOMAIN = "http://192.168.9.192/resource/crossdomain.xml";
			}
			
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.align = StageAlign.TOP_LEFT;
			Security.loadPolicyFile(CROSSDOMAIN);
			
			_netConnect = new NetConnection();
			_netConnect.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
			_netConnect.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			_netConnect.connect(null);
			
			_netStream = new NetStream(_netConnect);
			_netStream.bufferTime = .1;
			_netStream.play(null);
			_netStream.client = {};
			_netStream.client.onMetaData = ns_onMetaData;
			_netStream.client.onCurePoint = onCurePoint;
			
			_video = new Video();
			_video.x = 100;
			_video.y = 100;
			addChild(_video);
			_video.attachNetStream(_netStream);
			_netStream.appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN);
			_netStream.addEventListener(NetStatusEvent.NET_STATUS, netStreamStatusHandler);
			
			loading = new LoadingIndicator();
			loading.x = _video.x + (_video.width - loading.width)/2;
			loading.y = _video.y + (_video.height - loading.height)/2;
			addChild(loading);
			loading.visible = false;
			
			var btnPlus:RewindBtn = new RewindBtn();
			btnPlus.buttonMode = true;
			btnPlus.useHandCursor = true;
			btnPlus.addEventListener(MouseEvent.CLICK, clickPlusHandler);
			addChild(btnPlus);
			btnPlus.x = 316;
			btnPlus.y = _video.y + _video.height;
			
			var btnCut:ForwardBtn = new ForwardBtn();
			btnCut.buttonMode = true;
			btnCut.useHandCursor = true;
			btnCut.addEventListener(MouseEvent.CLICK, clickCutHandler);
			addChild(btnCut);
			btnCut.x = 100;
			btnCut.y = _video.y + _video.height;
			
			curTimeTxt.mouseEnabled = false;
			curTimeTxt.text = "当前时间:0.0/0.0";
			curTimeTxt.width = 200;
			addChild(curTimeTxt);
			curTimeTxt.x = _video.x + (_video.width - curTimeTxt.width)/2;
			curTimeTxt.y = _video.y + _video.height;
			
			loadedTxt.mouseEnabled = false;
			loadedTxt.text = "累计加载:0/0";
			loadedTxt.width = 200;
			addChild(loadedTxt);
			loadedTxt.x = _video.x + (_video.width - loadedTxt.width)/2;
			loadedTxt.y = _video.y + _video.height + curTimeTxt.height ;
			
			timer.addEventListener(TimerEvent.TIMER, timerHandler);
			timer.start();
		}
	
		private function timerHandler(evt:TimerEvent):void
		{
			if(_netStream.bufferLength <= .1)
			{
				loading.visible = true;
			}
			else
			{
				loading.visible = false;
			}
			curTimeTxt.text = "当前时间:";
			curTimeTxt.appendText((seektime + _netStream.time).toFixed(1).toString());
			curTimeTxt.appendText("/");
			curTimeTxt.appendText(duration.toFixed(1).toString());
			curTimeTxt.appendText("--");
			var perStr:String = (100 * (seektime + _netStream.time)/duration).toFixed(1) + "%";
			curTimeTxt.appendText(perStr);
			
			loadedTxt.text = "累计加载:";
			loadedTxt.appendText(loadedBytes.toString());
			loadedTxt.appendText("/");
			loadedTxt.appendText(endBytes.toString());
			loadedTxt.appendText("--");
			perStr =  (100 * loadedBytes/endBytes).toFixed(2) + "%";
			loadedTxt.appendText(perStr);
		}
		
		private function clickCutHandler(evt:MouseEvent):void
		{
			seektime = seektime + _netStream.time - 20;
			seek();
		}
		
		private function clickPlusHandler(evt:MouseEvent):void
		{
			seektime = seektime + _netStream.time + 30;
			seek();
		}
		
		private function seek():void
		{
			trace("seektime=" + seektime);
			
			if(seektime < 0 || seektime > duration)
			{
				seektime = 0;
			}
			
			nu=findKeyframe(seektime);
			_netStream.seek(seektime);
			loadedBytes = 0;
		}
		
		private function netStreamStatusHandler(event:NetStatusEvent):void 
		{
			switch (event.info.code) {
				case "NetConnection.Connect.Success":
					break;
				case "NetStream.Play.StreamNotFound":
					break;
				case "NetStream.Seek.Notify" :
					trace("NetStream Notify");
					_netStream.appendBytesAction(NetStreamAppendBytesAction.RESET_SEEK);
					nsUpdate(nu);
					break;
			}
		}
		
		private function nsUpdate(nu:Number):void
		{
			puppyLoader.loadBytes(nu, endBytes);
		}
		
		private function netStatusHandler(event:NetStatusEvent):void {
			switch (event.info.code) {
				case "NetConnection.Connect.Success":
					connectStream();
					break;
				case "NetStream.Play.StreamNotFound":
					trace("Stream not found: " + videoURL);
					break;
			}
		}
		
		
		private var puppyLoader:PuppyLoader;
		private function  connectStream():void
		{
			if(1)
			{
				puppyLoader = new PuppyLoader(videoURL);
				puppyLoader.addEventListener(PuppyEvent.RANGE_DATA_STREAMING, rangeDataStreamingHandler);
				puppyLoader.addEventListener(PuppyEvent.RANGE_DATA_COMPLETE, completeHandler);
				puppyLoader.loadBytes(0, 914212);
			}
		}
		
		private function findKeyframe(seekindex:int):Number
		{
			var index:Number=0;
			var keyTmp:String;
			var count1:int=0;
			var fileposition1:Number;
			//filepositions
			for(keyTmp in keyframes.times)
			{
				if(keyframes.times[keyTmp]>seekindex)
					break;
				index =keyframes.times[keyTmp];
				fileposition1  =keyframes.filepositions[keyTmp];
				
				count1++;
			}
			return fileposition1;				
		}
		
		private var loadedBytes:Number = 0;
		private var buffer:ByteArray = new ByteArray();
		private function rangeDataStreamingHandler(evt:PuppyEvent):void
		{
			evt.rangeBytes.readBytes(buffer, buffer.length, evt.rangeBytes.bytesAvailable);
			
			if(buffer.bytesAvailable >= 9)
			{
				loadedBytes += buffer.bytesAvailable;
				_netStream.appendBytes(buffer);
				buffer.clear();
			}
		}
		
		private function completeHandler(evt:PuppyEvent):void
		{
			trace("com lk");
			//var curData:ByteArray = evt.rangeBytes;
			//_netStream.appendBytes(curData);
		}
		
		private function onCurePoint(data:*):void
		{
			trace(data);
		}
		
		private function ns_onMetaData(data:Object):void
		{
			duration = data.duration;
			endBytes = data.filesize;
			
			var key:String; 
			var keyTmp:String;
			var x1:int=0;
			var x2:int=0;
			for (key in data) 
			{ 
				x1++;
				if(key=='keyframes')
				{
					keyframes=data[key];	
					x2=0;
					for(keyTmp in keyframes)
					{
						x2++;
					}
				}
				if(key=='seekpoints')
				{
					keyframes=data[key];	
					x2=0;
					for(keyTmp in keyframes)
					{
						x2++;
					}
				}
			}
		}
		
		private function securityErrorHandler(event:SecurityErrorEvent):void {
			trace("securityErrorHandler: " + event);
		}
	}
}